package com.lianziyou.coin.price.job;

import static com.lianziyou.coin.price.service.IGetPriceService.COIN_PRICE_REDIS_HASH_KEY;

import com.lianziyou.coin.price.service.IGetPriceService;
import com.lianziyou.coin.price.vo.PriceVO;
import java.math.BigDecimal;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.cloud.core.redis.RedisUtil;
import org.cloud.scheduler.constants.MisfireEnum;
import org.cloud.scheduler.job.BaseQuartzJobBean;
import org.cloud.utils.SpringContextUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CoinPriceJob extends BaseQuartzJobBean {

    final public static String redisLockerName = "system.common.CoinPriceJob.locker";

    @Override
    protected void init() {
        this.jobName = "价格获取定时任务";
        jobData.put("description", "价格获取定时任务,一分钟一次，具体的获取频率在实现中控制");
        this.jobTime = "0 0/1 * * * ? ";
        setMisfire(MisfireEnum.CronScheduleMisfireEnum.MISFIRE_INSTRUCTION_DO_NOTHING);
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        boolean locked = RedisUtil.single().getLock(redisLockerName, 3600 * 1000L);
        if (!locked) {
            return;
        }
        try {
            Map<String, IGetPriceService> priceBeans = SpringContextUtil.getApplicationContext().getBeansOfType(IGetPriceService.class);

            if (priceBeans == null || priceBeans.isEmpty()) {
                return;
            }

            if (RedisUtil.single().hashGet(COIN_PRICE_REDIS_HASH_KEY, "USDT_USDT") == null) {
                RedisUtil.single().hashSet(COIN_PRICE_REDIS_HASH_KEY, "USDT_USDT", PriceVO.builder().pairName("USDT_USDT").price(BigDecimal.ONE).build());
            }

            priceBeans.forEach((priceBeanName, priceBean) -> {
                try {
                    PriceVO priceVO = priceBean.getPrice();
                    if (priceVO != null) {
                        RedisUtil.single().hashSet(COIN_PRICE_REDIS_HASH_KEY, priceVO.getPairName(), priceVO);
                    }
                } catch (Exception e) {
                    log.error("{},get price error!,{}", priceBeanName, e);
                }
            });


        } finally {
            RedisUtil.single().releaseLock(redisLockerName);
        }
    }
}
